<?php

namespace app\index\controller;

use app\BaseController;
use think\facade\Db;
use think\facade\Request;
use think\facade\Session;
use think\response\Redirect;

class Order extends Common
{
    /**
     * 提交订单
     * @return string|Redirect
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function index()
    {
        if (Session::has('id') === false) {
            return redirect("/index/user/login");
        }
        $uid = Session::get("id");
        $address = Db::table("shop_address")->where("user_id",$uid)->select();
        $config = static::common();
        $carts = Db::table("shop_cart")
                ->alias("c")
                ->where("c.user_id",$uid)
                ->leftJoin(['shop_goods' => "g"],"c.goods_id = g.id")
                ->field(["c.*","g.title","g.image","g.price","g.discount"])
                ->select()
                ->toArray();
        // 商品件数、商品总金额
        $count = $total_price = 0;
        foreach ($carts as $v) {
            $count += $v["num"];
            $total_price += $v["price"] * $v["discount"] / 10 * $v["num"];
        }
        if (Request::method() == "POST"){
            $all = Request::param();
            Db::startTrans();
            try {
                foreach ($carts as $v){
                    $good = Db::table("shop_goods")->where("id",$v["goods_id"])->field("stock")->find();
                    // 判断库存是否足够
                    if ($v["num"] > $good["stock"]){
                        throw new \Exception("库存不足，请重新下单");
                    }
                    $order["order_no"] = date("YmdHis").rand(1000,9999);
                    $order["user_id"] = $uid;
                    $order["goods_id"] = $v["goods_id"];
                    $order["goods_num"] = $v["num"];
                    $order["goods_price"] = $v["price"];
                    $order["total_price"] = $v["price"] * $v["discount"] / 10 * $v["num"];
                    $order["pay_status"] = 0;
                    $order["pay_type"] = $all["pay_id"];
                    $order["add_time"] = $order["up_time"] = time();
                    Db::table("shop_order")->insert($order);
                    // 减商品库存
                    $good["stock"] -= $v["num"];
                    Db::table("shop_goods")->where("id",$v["goods_id"])->update($good);
                    // 清空购物车
                    Db::table("shop_cart")->where("id",$v["id"])->delete();
                    // 提交事务
                    Db::commit();
                }
            }catch (\Exception $e){
                // 回滚事务
                Db::rollback();
                echo "<script>alert('".$e->getMessage()."')</script>";
            }
        }
        MyViewAssign([
            "address" => $address,
            "payType" => $config['payType'],
            "carts" => $carts,
            "count" => $count,
            "total_price" => $total_price,
        ]);
        return MyView();
    }
}